package org.dromara.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.translation.annotation.Translation;
import org.dromara.study.domain.entity.Book;
import org.dromara.study.domain.entity.BookBorrowingRecords;
import org.dromara.study.domain.vo.BookBorrowingRecordsVo;
import org.dromara.study.mapper.BookBorrowingRecordsMapper;
import org.dromara.study.mapper.BookMapper;
import org.dromara.study.service.BookBorrowingRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookBorrowingRecordsServiceImpl extends ServiceImpl<BookBorrowingRecordsMapper, BookBorrowingRecords> implements BookBorrowingRecordsService {

    @Autowired
    private BookBorrowingRecordsMapper bookBorrowingRecordsMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public Page<BookBorrowingRecordsVo> getPage(PageQuery query, BookBorrowingRecordsVo bookBorrowingRecordsVo) {
        return bookBorrowingRecordsMapper.getPage(query.build(), bookBorrowingRecordsVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(BookBorrowingRecordsVo bookBorrowingRecordsVo) {
//        Long count = bookBorrowingRecordsMapper.selectCount(new LambdaQueryWrapper<BookBorrowingRecords>().eq(bookBorrowingRecordsVo.getBookId() != null, BookBorrowingRecords::getBookId, bookBorrowingRecordsVo.getBookId()));
        Book book = bookMapper.selectOne(new LambdaQueryWrapper<Book>().eq(bookBorrowingRecordsVo.getBookId() != null, Book::getId, bookBorrowingRecordsVo.getBookId()));
        if (book == null) {
            throw new RuntimeException("没有找到该图书");
        }
        if (book.getStock() <= 0) {
            throw new RuntimeException("该图书数量不足");
        }
        book.setStock(book.getStock() - 1);
        bookMapper.updateById(book);
        bookBorrowingRecordsMapper.insert(bookBorrowingRecordsVo);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean returnBook(BookBorrowingRecordsVo bookBorrowingRecordsVo) {
        Book book = bookMapper.selectOne(new LambdaQueryWrapper<Book>().eq(bookBorrowingRecordsVo.getBookId() != null, Book::getId, bookBorrowingRecordsVo.getBookId()));
        book.setStock(book.getStock() + 1);
        bookMapper.updateById(book);
        bookBorrowingRecordsMapper.updateById(bookBorrowingRecordsVo);
        return true;
    }
}
